package com.czm.art_light.util;

import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.exception.BusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * JSON 工具类
 */
@Slf4j
public final class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象序列化成JSON
     */
    public static String objToJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("JSON 序列化异常：{}", e.getMessage(), e);
            throw new BusinessException(ArtErrorCodeEnum.JSON_SERIALIZE_ERROR);
        }
    }

    /**
     * 将 JSON 反序列化成指定类型
     */
    public static <T> T jsonToObj(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error("JSON 反序列化异常：{}", e.getMessage(), e);
            throw new BusinessException(ArtErrorCodeEnum.JSON_DESERIALIZE_ERROR);
        }
    }
}
